<template>
  <div class="problem-container">
    <!-- 标题区优化 -->
    <div class="header-section">
      <div class="title-wrapper">
        <h1 class="problem-title">
          {{ problem.title }}
          <el-tag 
            :type="difficultyType" 
            effect="light"
            class="difficulty-tag">
            <i :class="difficultyIcon" class="iconfont"></i>
            {{ difficultyText }}
          </el-tag>
        </h1>
        <div class="meta-info">
          <div class="stat-item">
            <i class="el-icon-document"></i>
            <span class="stat-value">{{ problem.submitCount || 0 }}</span>
            <span class="stat-label">次提交</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 内容区优化 -->
    <div class="content-section">
      <!-- 左侧描述区 -->
      <el-card class="description-panel">
        <h3 class="section-title">
          <i class="el-icon-notebook-2"></i>
          题目描述
        </h3>
        <pre class="content-text">{{ problem.description }}</pre>

        <!-- 样例展示优化 -->
        <template v-if="publicTestCases.length">
          <h3 class="section-title">
            <i class="el-icon-tickets"></i>
            示例
          </h3>
          <div 
            v-for="(testCase, index) in publicTestCases" 
            :key="index"
            class="testcase-card">
            <div class="io-group">
              <div class="io-item">
                <div class="io-header">
                  <span class="io-label">输入</span>
                  <el-button 
                    size="mini" 
                    type="text"
                    @click="copyText(testCase.input)">
                    <i class="el-icon-document-copy"></i>
                  </el-button>
                </div>
                <pre class="io-content">{{ testCase.input }}</pre>
              </div>
              <div class="io-item">
                <div class="io-header">
                  <span class="io-label">输出</span>
                  <el-button 
                    size="mini" 
                    type="text"
                    @click="copyText(testCase.output)">
                    <i class="el-icon-document-copy"></i>
                  </el-button>
                </div>
                <pre class="io-content">{{ testCase.output }}</pre>
              </div>
            </div>
          </div>
        </template>
      </el-card>

      <!-- 右侧编辑区优化 -->
      <el-card class="editor-panel">
        <div class="editor-header">
          <el-select
            v-model="currentLanguage"
            placeholder="选择语言"
            class="lang-selector"
            size="medium">
            <i slot="prefix" class="el-icon-cpu"></i>
            <el-option
              v-for="lang in languages"
              :key="lang.value"
              :label="lang.label"
              :value="lang.value"/>
          </el-select>
          <el-button
            type="primary"
            size="medium"
            :loading="submitting"
            @click="handleSubmit"
            class="submit-btn">
            <i class="el-icon-upload2"></i>
            提交代码
          </el-button>
        </div>
        <div class="editor-wrapper">
          <div ref="editor" class="code-editor"></div>
          <div class="code-tip">
            <i class="el-icon-info"></i>
            支持自动补全 (Ctrl+Space)
          </div>
        </div>
      </el-card>

      <!-- 运行结果面板 -->
      <transition name="slide-fade">
        <el-card v-if="showResult" class="result-panel">
          <div class="result-header">
            <h3>运行结果</h3>
            <el-button 
              type="text" 
              icon="el-icon-close" 
              @click="showResult = false">
            </el-button>
          </div>
          <el-timeline>
            <el-timeline-item 
              v-for="(log, index) in resultLogs" 
              :key="index" 
              :timestamp="log.timestamp">
              {{ log.message }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </transition>
    </div>
  </div>
</template>

<script>
import { getProblem, submitCode, getSubmissionResult } from '@/api/problem/problem'
import ace from 'ace-builds'
import 'ace-builds/webpack-resolver'
// ACE 代码编辑器模式映射
const MODE_MAP = {
  javascript: 'javascript',
  python: 'python',
  java: 'java',
  cpp: 'c++'
}

export default {
  name: 'ProblemDetail',
  data() {
    return {
      problem: {
        id: null, // 确保有 problemId
        title: '',
        description: '',
        difficulty: 'EASY',
        tags: [],
        submitCount: 0,
        testCaseList: []
      },
      userId: null, // 需要从用户数据获取
      currentLanguage: 'javascript',
      languages: [
        { label: 'JavaScript', value: 'javascript' },
        { label: 'Python 3', value: 'python' },
        { label: 'Java 11', value: 'java' },
        { label: 'C++ 17', value: 'cpp' }
      ],
      editor: null,
      submitting: false,
      showResult: false,
      resultLogs: [],
      submissionId: null,
    }
  },
  computed: {
    // 获取难度对应的颜色
    difficultyType() {
      const map = { easy: 'success', medium: 'warning', hard: 'danger' }
      return map[this.problem.difficulty?.toLowerCase()] || 'info'
    },
    difficultyText() {
      const map = { easy: '简单', medium: '中等', hard: '困难' }
      return map[this.problem.difficulty?.toLowerCase()] || '未知难度'
    },
    // 获取公开测试用例
    publicTestCases() {
      return this.problem.testCaseList?.filter(tc => tc.isPublic === 1) || []
    }
  },
  mounted() {
    this.initEditor()
    this.loadProblem()
    this.loadUser()
  },
  methods: {
    copyText(text) {
      navigator.clipboard.writeText(text)
      this.$message.success('已复制到剪贴板')
    },
    async loadUser() {
      try {
        const res = await this.$store.dispatch('GetInfo')
        this.userId = res.user?.userId || null
        console.log('用户信息加载成功:', res.user)
      } catch (error) {
        console.error('用户信息加载失败:', error)
      }
    },
    async loadProblem() {
      try {
        const { data } = await getProblem(this.$route.params.id)
        this.problem = {
          ...this.problem,
          ...data,
          id: data.id || null,
          tags: data.tags || []
        }
      } catch (error) {
        this.$message.error('题目加载失败')
        console.error('题目加载错误:', error)
      }
    },
    initEditor() {
      this.$nextTick(() => {
        ace.config.set('basePath', 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/')

        this.editor = ace.edit(this.$refs.editor, {
          mode: `ace/mode/${MODE_MAP[this.currentLanguage]}`,
          theme: 'ace/theme/chrome',
          fontSize: 14,
          tabSize: 2,
          showPrintMargin: false,
          scrollPastEnd: true,
          autoScrollEditorIntoView: true
        })

        // 配置滚动条
        this.editor.renderer.setScrollMargin(10, 10, 10, 10)
        this.editor.renderer.setPadding(16)
      })
    },
    async handleSubmit() {
      if (!this.userId) {
        this.$message.error('用户未登录或未获取到用户信息');
        return;
      }
      if (!this.problem.id) {
        this.$message.error('题目数据未正确加载');
        return;
      }
      const code = this.editor.getValue();
      if (!code.trim()) {
        this.$message.error('代码不能为空');
        return;
      }

      this.submitting = true;
      this.showResult = true; // 提交后自动展开
      this.resultLogs = [{ timestamp: new Date().toLocaleTimeString(), message: '代码提交中...' }];

      try {
        const response = await submitCode({
          problemId: this.problem.id,
          userId: this.userId,
          language: this.currentLanguage,
          code: code
        });

        const submissionId = typeof response.data === 'number' ? response.data : response.data?.data;

        if (!submissionId) {
          throw new Error('提交失败，服务器未返回提交 ID');
        }

        console.log('提交成功，submissionId:', submissionId);
        this.pollResult(submissionId);
      } catch (error) {
        console.error('提交代码失败:', error);
        this.resultLogs.push({
          timestamp: new Date().toLocaleTimeString(),
          message: error.message || '提交失败，请稍后重试'
        });
      } finally {
        this.submitting = false;
      }
    },

    async pollResult(submissionId) {
      console.log('pollResult 被调用，submissionId:', submissionId)

      if (!submissionId) {
        console.error('submissionId 不能为空')
        this.resultLogs.push({ timestamp: new Date().toLocaleTimeString(), message: '提交ID无效' })
        return
      }

      const interval = setInterval(async () => {
        try {
          console.log('发送请求到后端，submissionId:', submissionId)
          const response = await getSubmissionResult(submissionId)  // 调用API
          console.log('后端返回:', response)

          if (!response || !response.data) {
            throw new Error('后端未返回数据')
          }

          const data = response.data
          this.resultLogs.push({ timestamp: new Date().toLocaleTimeString(), message: `状态: ${data.status}` })

          if (data.status && data.status !== 'Pending') {
            clearInterval(interval)  // 任务完成，停止轮询
          }
        } catch (error) {
          console.error('查询提交结果失败:', error)
          clearInterval(interval)
          this.resultLogs.push({ timestamp: new Date().toLocaleTimeString(), message: '查询失败' })
        }
      }, 2000)
    }
  }
}
</script>

<style lang="scss" scoped>
.problem-container {
  max-width: 1440px;
  margin: 0 auto;
  padding: 24px;

  .header-section {
    margin-bottom: 32px;
    padding: 24px;
    background: linear-gradient(145deg, #f8faff, #ffffff);
    border-radius: 12px;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);

    .problem-title {
      font-size: 32px;
      color: #2c3e50;
      margin: 0 0 16px;
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .difficulty-tag {
      font-size: 14px;
      padding: 6px 12px;
      border-radius: 6px;
      i {
        margin-right: 6px;
      }
    }

    .stat-item {
      display: inline-flex;
      align-items: center;
      padding: 8px 16px;
      background: #f5f7fa;
      border-radius: 8px;
      i {
        margin-right: 8px;
        color: #409eff;
      }
      .stat-value {
        font-size: 16px;
        color: #303133;
        margin: 0 4px;
      }
      .stat-label {
        color: #909399;
        font-size: 13px;
      }
    }
  }

  .content-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;

    .description-panel, .editor-panel {
      border: none;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
      transition: box-shadow 0.3s ease;

      &:hover {
        box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
      }
    }

    .section-title {
      color: #2c3e50;
      font-size: 18px;
      margin: 0 0 20px;
      display: flex;
      align-items: center;
      i {
        margin-right: 8px;
        font-size: 20px;
      }
    }

    .content-text {
      font-size: 14px;
      line-height: 1.8;
      color: #5e6d82;
      background: #f8f9fc;
      padding: 16px;
      border-radius: 8px;
      border: 1px solid #ebeef5;
    }

    .testcase-card {
      background: #f8f9fc;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;

      .io-item {
        background: white;
        border-radius: 6px;
        padding: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

        .io-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .io-label {
            color: #409eff;
            font-size: 13px;
            font-weight: 500;
          }

          button {
            padding: 4px;
            i {
              font-size: 14px;
              color: #909399;
            }
          }
        }

        .io-content {
          font-family: 'JetBrains Mono', monospace;
          font-size: 13px;
          color: #304455;
          background: #fafbfc;
          padding: 8px;
          border-radius: 4px;
          border: 1px solid #e4e7ed;
        }
      }
    }

    .editor-panel {
      .editor-header {
        margin-bottom: 16px;
        display: flex;
        gap: 12px;

        .lang-selector {
          flex: 1;
          ::v-deep .el-input__prefix {
            display: flex;
            align-items: center;
            padding-left: 10px;
            i {
              color: #409eff;
            }
          }
        }

        .submit-btn {
          padding: 10px 24px;
          i {
            margin-right: 6px;
          }
        }
      }

      .editor-wrapper {
        height: 640px;
        border-radius: 8px;
        overflow: hidden;
        position: relative;

        .code-editor {
          height: 100%;
          &::-webkit-scrollbar {
            width: 6px;
            background: transparent;
          }
          &::-webkit-scrollbar-thumb {
            background: #c0c4cc;
            border-radius: 4px;
          }
        }

        .code-tip {
          position: absolute;
          bottom: 16px;
          right: 16px;
          background: rgba(255, 255, 255, 0.9);
          padding: 6px 12px;
          border-radius: 16px;
          font-size: 12px;
          color: #909399;
          backdrop-filter: blur(4px);
          i {
            margin-right: 4px;
          }
        }
      }
    }
  }
}
.slide-fade-enter-active, .slide-fade-leave-active {
  transition: all 0.3s ease-in-out;
}
.slide-fade-enter, .slide-fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 运行结果面板 */
.result-panel {
  position: absolute;
  bottom: 0;
  width: 38.5%;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 10px;
  border-radius: 5px;
  margin-left: 47%;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 代码编辑器 */
.editor-wrapper {
  position: relative;
}

.code-tip {
  font-size: 12px;
  color: #666;
  text-align: right;
  margin-top: 5px;
}
@media (max-width: 1200px) {
  .problem-container {
    padding: 16px;
    
    .content-section {
      grid-template-columns: 1fr;
      gap: 16px;

      .editor-wrapper {
        height: 480px !important;
      }
    }
  }
}
</style>